package xj.graph2d.command;

import java.awt.geom.Rectangle2D;

import xj.graph2d.DrawShape;
import xj.graph2d.Group;
import xj.graph2d.SimpleDrawDocument;
import xj.graph2d.SimpleDrawView;

public class GroupCommand extends AbstractCommand {

  public GroupCommand(SimpleDrawView view, SimpleDrawDocument doc, Group group,
      Group prevGroup) {
    super(view, doc);
    this.group = group;
    this.prevGroup = prevGroup;
  }

  public void execute() {
    if (group != null) {
      DrawShape selected = doc.getSelectedShape();
      doc.setSelectedShape(null);
      canvas.repaintShape(selected);
      group.activate();
      if (prevGroup != null && prevGroup == doc.getGroup()) {
	doc.ungroup();
      }
      if (group != doc.getGroup()) {
	doc.setGroup(group, true);
      }
      doc.setSelectedShape(group);
      canvas.repaintShape(group);
    }
  }

  public void undo() {
    if (group != null) {
      Rectangle2D r = group.getBounds();
      doc.ungroup();
      canvas.repaintRect(r, true);
      DrawShape selected = doc.getSelectedShape();
      doc.setSelectedShape(null);
      canvas.repaintShape(selected);

      if (prevGroup != null) {
	prevGroup.activate();
	doc.setGroup(prevGroup, true);
	doc.setSelectedShape(prevGroup);
	r = prevGroup.getBounds();
	canvas.repaintRect(r, true);
      }
    }
  }

  protected Group group;

  protected Group prevGroup;

}
